//
//  BuyViewController.m
//  体育商城
//
//  Created by  on 2022/9/23.
//

#import "BuyViewController.h"
#import "BuyCell.h"
#import "BuyDetailCell.h"
#import "BuyHeader.h"
#import "PayViewController.h"
#import "BuyDetailPopViewController.h"
#import "SubmitOrderViewController.h"
#import "FavoriteViewController.h"

@interface BuyViewController ()
@property (strong, nonatomic) IBOutlet UIView *toolbar;
@property (assign, nonatomic)  CGFloat headerH;
@property (nonatomic,strong) NSArray *array;
@end

@implementation BuyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    [self initUI];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    BOOL a = self.navigationController.viewControllers[self.navigationController.viewControllers.count - 1].navigationController.navigationBar.hidden;
    [self.navigationController setNavigationBarHidden:YES animated:!a];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    BOOL a = self.navigationController.viewControllers[self.navigationController.viewControllers.count - 1].navigationController.navigationBar.hidden;
    [self.navigationController setNavigationBarHidden:NO animated:!a];
}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [self.view sendSubviewToBack:self.collectionView];
}
- (void)initUI{
    [self.collectionView registerNib:[BuyCell nib] forCellWithReuseIdentifier:[BuyCell ID]];
    [self.collectionView registerNib:[BuyDetailCell nib] forCellWithReuseIdentifier:[BuyDetailCell ID]];
    [self.collectionView registerNib:[BuyHeader nib] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:[BuyHeader ID]];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"sectionview"];

    NSLayoutConstraint *top = [self.collectionView a1:NSLayoutAttributeTop e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeTop c:0];
    NSLayoutConstraint *left = [self.collectionView a1:NSLayoutAttributeLeft e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeLeft c:0];
    NSLayoutConstraint *right = [self.collectionView a1:NSLayoutAttributeRight e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeRight c:0];
    NSLayoutConstraint *bottom = [self.collectionView a1:NSLayoutAttributeBottom e:NSLayoutRelationEqual t:self.toolbar a2:NSLayoutAttributeTop c:0];
    [self.view addConstraints:@[top,left,right,bottom]];
}
- (void)loadData{
    NSString *style = [NSString stringWithFormat:@"%@%@",self.model.colour,self.model.sortOrder];
    self.array = @[@{LS(@"选择"):style},@{LS(@"发货"):LS(@"中国.北京")},@{LS(@"运费"):LS(@"免运费")},@{LS(@"保障"):LS(@"保价服务，正品保障")}];
}

- (IBAction)actionForBtn:(UIButton *)sender {
    if (sender.tag == 200) {
        return [self backBtnAction];
    }
    if (APP.user.account ==  nil || APP.user.account.length <= 0) {
        return [Toast msg:LS(@"您还未登录，请先去登录")];
    }

    if ([sender.currentTitle isEqualToString:LS(@"收藏")]) {
        if (self.model.orderStatus == GoodsOrderStastusFavorite) {
            sender.enabled = NO;
            return [Toast startHud:LS(@"已收藏") stopTime:1 handle:^{
                FavoriteViewController *vc = [FavoriteViewController new];
                [self.navigationController pushViewController:vc animated:YES];
                sender.enabled = YES;
            }];
        }
        self.model.account = APP.user.account;
        self.model.payNum = @"1";
        self.model.address = APP.user.address;
        self.model.orderStatus = GoodsOrderStastusFavorite;
        self.model.orderID = [NSDate currentTimeStamp:@"yyyy/MM/dd HH:mm:ss"];
        [self.model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [Toast msg:LS(@"收藏成功")];
            });
        }];
    }else if ([sender.currentTitle isEqualToString:LS(@"加入购物车")]){
        self.model.account = APP.user.account;
        self.model.payNum = @"1";
        self.model.address = APP.user.address;
        self.model.orderStatus = GoodsOrderStastusJoinCart;
        BuyDetailPopViewController *vc = [BuyDetailPopViewController new];
        vc.model = self.model;
        WS(self)
        vc.block = ^{
            weakself.model.orderID = [NSDate currentTimeStamp:@"yyyy/MM/dd HH:mm:ss"];
            [weakself.model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:notifyJoinCartUpdate object:nil];
                });
            }];
        };
        [self presentViewController:vc animated:YES completion:nil];
    }else if ([sender.currentTitle isEqualToString:LS(@"立即购买")]){
        SubmitOrderViewController * vc = [SubmitOrderViewController new];
        vc.model = self.model;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return  2;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return  section == 0 ? self.array.count : 1;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        BuyCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:[BuyCell ID] forIndexPath:indexPath];
       NSDictionary *dict = self.array[indexPath.row];
        cell.title.text = [[dict allKeys] firstObject];
        cell.content.text = [[dict allValues] firstObject];
        return  cell;
    }else{
        BuyDetailCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:[BuyDetailCell ID] forIndexPath:indexPath];
        cell.model = self.model;
        return  cell;
    }
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    NSString *ids = indexPath.section == 0 ? [BuyHeader ID] : @"sectionview";
    UICollectionReusableView * view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:ids forIndexPath:indexPath];
    if (indexPath.section == 0) {
        BuyHeader * header = (BuyHeader*)view;
        header.model = self.model;
        return  view;
    }else{
        view.backgroundColor = [UIColor clearColor];
        return view;
    }
}
#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
}
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
  
    if ((indexPath.row == 0 || indexPath.row == 3) && indexPath.section == 0) {
        UIRectCorner cor = indexPath.row == 0 ? (UIRectCornerTopLeft | UIRectCornerTopRight) : (UIRectCornerBottomLeft | UIRectCornerBottomRight);
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:cell.bounds byRoundingCorners:cor cornerRadii:CGSizeMake(8, 8)];
        CAShapeLayer *layer = [CAShapeLayer new];
        layer.frame = cell.bounds;
        layer.path = path.CGPath;
        cell.layer.mask = layer;
    }else{
        cell.layer.mask = nil;
    }
}
#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return CGSizeMake(SCREEN_WIDTH - 20, 50);
    }else{
       NSString *str = [NSString stringWithFormat:@"%@ %@",self.model.name,self. model.shortDescription];
       CGSize size = [str sizeWithFont:[UIFont systemFontOfSize:14] inWidth:SCREEN_WIDTH - 40];
        CGFloat h = indexPath.row != 0 ? (SCREEN_WIDTH - 20) : (SCREEN_WIDTH - 20) + 191 + ceil(size.height) ;
        return CGSizeMake(SCREEN_WIDTH - 20, h);
    }
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return  UIEdgeInsetsMake(10, 10, 10, 10);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return CGSizeMake(SCREEN_WIDTH, SCREEN_WIDTH + 80);
    }else{
        return CGSizeMake(SCREEN_WIDTH, 10);
    }
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeZero;
}


@end
